﻿using System;

namespace Infrastructure.Device
{
    /// <summary>
    /// 注册表操作
    /// </summary>
    public static class RegistryEditor
    {
        /// <summary> 
        /// 设置程序开机启动 
        /// 或取消开机启动 
        /// </summary> 
        /// <param name="isEnabled">设置开机启动，或者取消开机启动</param> 
        /// <param name="exeName">注册表中程序的名字</param> 
        /// <param name="path">开机启动的程序路径</param> 
        /// <returns>开启或则停用是否成功</returns> 
        public static bool AutoStart(bool isEnabled, string exeName, string path)
        {
            using (var key = InitKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run"))
            {
                try
                {
                    if (isEnabled)
                    {
                        key?.SetValue(exeName, path);//设置为开机启动 
                    }
                    else
                    {
                        key?.DeleteValue(exeName);//取消开机启动 
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="paramName">参数名称</param>
        /// <param name="value">值</param>
        public static void SetValue(string path, string paramName, object value)
        {
            using (var key = InitKey(path))
            {
                key.SetValue(paramName, value);
            }
        }

        /// <summary>
        /// 获得值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="path">路径</param>
        /// <param name="paramName">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static T GetValue<T>(string path, string paramName, T defaultValue)
        {
            using (var key = InitKey(path))
            {
                var obj = key.GetValue(paramName);
                if (obj == null)
                {
                    obj = defaultValue;
                    key.SetValue(paramName, defaultValue);
                }

                return (T)Convert.ChangeType(obj, typeof(T));
            }

        }

        /// <summary>
        /// 初始化注册表
        /// 位于CurrentUser
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static Microsoft.Win32.RegistryKey InitKey(string path)
        {
            // var subPath = $"Software\\{path}";
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(path, true);
            if (key == null)
            {
                key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(path);
            }
            return key;
        }
    }
}
